import 'dart:collection';
import 'dart:io';

import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:jm_flutter_common/jm_flutter_common.dart';
import '../../../common/utils/shortcut.dart';
import '../../../common/utils/show.dart';
import '../../../config.dart';
import '../../resources/resources.dart';
import '../../widget/widget.dart';
import 'app_file_txt_view_page.dart';
import 'controller/selection_controller.dart';
import 'model/app_file_desc.dart';
import 'model/app_file_list_adapter.dart';
import 'util/app_file_util.dart';
import 'widget/directory_navigation_bar.dart';
import 'widget/file_list_item.dart';

class AppFilePage extends StatefulWidget {
  final bool selectFile;

  const AppFilePage({super.key, this.selectFile = false});

  @override
  State<AppFilePage> createState() => _AppFilePageState();
}

class _AppFilePageState extends State<AppFilePage> {
  final tag = "AppFilePage";

  final AppFileSelectionController selectionController = findSelection;

  final Queue<AppFileDesc> dirQueue = Queue();
  AppFileDesc rootDir = AppFileDesc(name: "AppDoc", path: JmConfig.appDocPath!);
  final adapter = AppFileListAdapter();

  bool isTempDir = false;

  bool get isSelectMode => selectionController.isSelectMode;

  init() async {
    pushRootDir();
  }

  void pushRootDir() async {
    adapter.files.clear();
    adapter.files.addAll(await AppFileUtil.getFiles(dirPath: rootDir.path));
    adapter.dirPath = rootDir.path;
    dirQueue.clear();
    setState(() {});
  }

  void pushDir(AppFileDesc fileDesc) async {
    dirQueue.addLast(fileDesc);
    adapter.files.clear();
    adapter.files.addAll(await AppFileUtil.getFiles(dirPath: fileDesc.path));
    adapter.dirPath = fileDesc.path;
    adapter.currentDir = fileDesc;
    setState(() {});
  }

  void popDir(AppFileDesc fileDesc) async {
    if (dirQueue.isEmpty) {
      return;
    }

    while (dirQueue.isNotEmpty) {
      if (dirQueue.last.path == fileDesc.path) {
        break;
      }
      dirQueue.removeLast();
    }

    if (dirQueue.isEmpty) {
      pushRootDir();
      return;
    }

    final lastFileDesc = dirQueue.last;
    adapter.files.clear();
    adapter.files
        .addAll(await AppFileUtil.getFiles(dirPath: lastFileDesc.path));
    adapter.dirPath = lastFileDesc.path;
    adapter.currentDir = lastFileDesc;
    setState(() {});
  }

  void upFiles() async {
    adapter.files.clear();
    adapter.files.addAll(await AppFileUtil.getFiles(dirPath: adapter.dirPath));
    setState(() {});
  }

  void switchFolder() {
    isTempDir = !isTempDir;
    if (isTempDir) {
      rootDir = AppFileDesc(name: "AppTemp", path: JmConfig.appTempPath!);
      logd(tag, "切换到临时文件夹: ${JmConfig.appTempPath}");
    } else {
      rootDir = AppFileDesc(name: "AppDoc", path: JmConfig.appDocPath!);
      logd(tag, "切换到文档文件夹: ${JmConfig.appDocPath}");
    }
    pushRootDir();
  }

  void appCachePath() {
    rootDir = AppFileDesc(name: "AppCache", path: JmConfig.appCachePath!);
    logd(tag, "切换到缓存文件夹: ${JmConfig.appCachePath}");
    pushRootDir();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    init();
  }

  @override
  Widget build(BuildContext context) {
    return Obx(
      () => MyScaffold(
        i18n: false,
        title: widget.selectFile
            ? "请选择文件"
            : isSelectMode
                ? "已选择${selectionController.selectedCount}个文件"
                : isTempDir
                    ? "App临时文件"
                    : "App文件",
        actions: isSelectMode
            ? [
                TextButton(
                  onPressed: () {
                    selectionController.exitSelectMode();
                  },
                  child: MyText(
                    "取消",
                    //color: Colors.white,
                  ),
                ),
                IconButton(
                  onPressed: () {
                    selectionController.selectedList(adapter.files);
                  },
                  icon: const Icon(Icons.check_box),
                ),
              ]
            : [
                IconButton(
                    icon: const Icon(CupIcons.folder_badge_person_crop),
                    onPressed: () {
                      appCachePath();
                    }),
                IconButton(
                    icon: const Icon(CupIcons.arrow_right_arrow_left),
                    onPressed: () {
                      switchFolder();
                    }),
                // IconButton(
                //     icon: const Icon(CupIcons.refresh),
                //     onPressed: () {
                //       upFiles();
                //     }),
              ],
        body: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: AppDirectoryNavigationBar(
                dirQueue: dirQueue,
                rootDir: rootDir,
                onTapRootDir: () {
                  pushRootDir();
                },
                onTapDir: (AppFileDesc dir) {
                  if (dir != adapter.currentDir) {
                    popDir(dir);
                  }
                },
              ),
            ),
            Expanded(
              child: adapter.isEmpty
                  ? Center(
                      child: MyText.sub("暂无文件"),
                    )
                  : ListView.separated(
                      padding: EdgeInsets.zero,
                      itemCount: adapter.count,
                      itemBuilder: (context, index) {
                        final file = adapter.files[index];
                        //是否是最后一个

                        return AppFileListItem(
                          fileDesc: file,
                          isSelected: selectionController.isSelected(file),
                          selectedMode: isSelectMode,
                          onTap: () {
                            if (selectionController.isSelectMode) {
                              selectionController.selectedFile(file);
                              return;
                            }

                            if (file.isDir) {
                              pushDir(file);
                              return;
                            }

                            if (widget.selectFile) {
                              back(result: file.path);
                              return;
                            }

                            if (file.extension == "bak" ||
                                file.extension == "gs" ||
                                file.extension == "txt" ||
                                file.extension == "json") {
                              goto(() => AppTextFileViewPage(fileDesc: file));
                            }
                          },
                          onLongPress: () {
                            if (!selectionController.isSelectMode) {
                              selectionController.isSelectMode = true;
                              selectionController.selectedFile(file);
                              return;
                            }
                          },
                        );
                      },
                      separatorBuilder: (BuildContext context, int index) {
                        // final file = adapter.files[index];
                        //
                        // if (file.hiddenFile) {
                        //   return Container();
                        // }
                        //return Container();
                        return div(
                          indent: 75,
                          thickness: 0.333,
                        );
                      },
                    ),
            ),
          ],
        ),
        floatingActionButton: isSelectMode
            ? null
            : FloatingActionButton(
                onPressed: () async {
                  upFiles();
                },
                child: const Icon(CupIcons.refresh),
              ),
        bottomNavigationBar: isSelectMode
            ? Container(
                padding: const EdgeInsets.only(top: 4, bottom: 2),
                child: SafeArea(
                  top: false,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      MyIconTextButton(
                          icon: const Icon(CupIcons.share),
                          text: "发送",
                          onPressed: () async {
                            await AppFileUtil.shareFiles(
                                selectionController.selectedFiles);
                            selectionController.exitSelectMode();
                          }),
                      MyIconTextButton(
                          icon: const Icon(CupIcons.delete),
                          text: "删除",
                          color: Colors.red,
                          onPressed: () {
                            MyDialog(title: "是否删除文件", actions: [
                              MyDialogAction.cancel(),
                              MyDialogAction(
                                  text: "删除",
                                  bold: false,
                                  textColor: Colors.red,
                                  onTap: () {
                                    back();
                                    Show.loading(str: "正在删除");
                                    AppFileUtil.deleteFiles(
                                            selectionController.selectedFiles)
                                        .then((value) {
                                      Show.success("删除成功");
                                      upFiles();
                                    });
                                    selectionController.exitSelectMode();
                                  }),
                            ]).show();
                          }),
                      MyIconTextButton(
                          icon: const Icon(CupIcons.info),
                          text: "属性",
                          onPressed: () async {
                            logd(tag, "属性: ${adapter.currentDir.path}");
                          }),
                    ],
                  ),
                ),
              )
            : null,
      ),
    );
  }
}
